import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'

//用户角色定义
export type UserRole = 'admin' | 'user' | null

export interface AuthState {
    accessToken: string | null
    refreshToken: string | null
    accessTokenExpiresAt: number | null
    role: UserRole
    username: string | null
}

const initialState: AuthState = {
    accessToken: null,
    refreshToken: null,
    accessTokenExpiresAt: null,
    role: null,
    username: null,
}

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        setCredentials: (
            state,
            action: PayloadAction<{ accessToken: string; refreshToken: string; accessTokenExpiresAt: number; role: UserRole; username: string }>
        ) => {
            state.accessToken = action.payload.accessToken
            state.refreshToken = action.payload.refreshToken
            state.accessTokenExpiresAt = action.payload.accessTokenExpiresAt
            state.role = action.payload.role
            state.username = action.payload.username
        },
        clearAuth: (state) => {
            state.accessToken = null
            state.refreshToken = null
            state.accessTokenExpiresAt = null
            state.role = null
            state.username = null
        },
    },
})

export const { setCredentials, clearAuth } = authSlice.actions
export default authSlice.reducer

